package com.tg.app.activity.device.list;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextPaint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.appbase.custom.constant.CommonConstants;
import com.base.BaseFragment;
import com.bumptech.glide.Glide;
import com.bumptech.glide.ListPreloader;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.integration.recyclerview.RecyclerViewPreloader;
import com.bumptech.glide.util.FixedPreloadSizeProvider;
import com.demo.bannerview.BannerViewPager;
import com.demo.bannerview.ViewBindingSampleAdapter;
import com.demo.bannerview.constants.IndicatorGravity;
import com.demo.bannerview.indicator.enums.IndicatorSlideMode;
import com.demo.bannerview.indicator.enums.IndicatorStyle;
import com.demo.view.TGSwipeRefreshLayout;
import com.magicindicator.buildins.UIUtil;
import com.tange.base.toolkit.DimenUtil;
import com.tange.base.toolkit.PreferenceUtil;
import com.tg.app.R;
import com.tg.app.activity.device.MultiPlayerActivity;
import com.tg.app.adapter.DeviceAdapter;
import com.tg.app.adapter.DeviceListAdapter;
import com.tg.app.helper.DeviceHelper;
import com.tg.app.util.LogUtils;
import com.tg.app.widget.CommItemDecoration;
import com.tg.appcommon.android.ImageUtils;
import com.tg.appcommon.android.ResourcesUtil;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.data.bean.DeviceItem;
import com.tg.data.http.entity.MessageDataBean;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;


public abstract class DeviceListBaseFragment extends BaseFragment implements
        View.OnClickListener, DeviceAdapter.OnItemClickListener, DeviceAdapter.OnNoItemClickListener {

    protected static final String PARAM_SHOW_TOP_BAR = "PARAM_SHOW_TOP_BAR";
    private static final int MAX_PAGER = 14;
    protected ImageButton drawMenu, btnCardAdd, btnListAdd, btnDisplayChanged;
    protected DeviceAdapter mAdapter;
    protected TGSwipeRefreshLayout swipeRefreshLayout;
    private RelativeLayout emptyLayout;
    protected RecyclerView recyclerView;
    protected CopyOnWriteArrayList<DeviceItem> deviceList = new CopyOnWriteArrayList<>();
    private BannerViewPager<Integer> mViewPager;
    private static final int imageWidthPixels = 640;
    private static final int imageHeightPixels = 360;

    private PopupWindow mMoreWindow;
    private LinearLayoutManager linearLayoutManager;
    protected boolean isLocalList = false;
    protected boolean isListDisplay = false;

    protected DrawerLayout mDrawerLayout;
    private int statusBarHeight;
    protected  HashMap<String,MessageDataBean> mDoorbellMaps = new HashMap<>();
    protected int devicePage = 1;
    protected int deviceCount = -1;

    private MineViewContainer mineViewContainer;

    protected boolean shouldShowTopBar = true;

    protected View rootView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            shouldShowTopBar = getArguments().getBoolean(PARAM_SHOW_TOP_BAR, true);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.activity_tange_device_list, container, false);
        initRootView();
        return rootView;
    }

    public <T extends View> T findViewById(@IdRes int id) {
        if (rootView == null) return null;
        return rootView.findViewById(id);
    }

    protected void  initRootView() {

        // 展示顶部栏的时候，才需要初始化侧边栏
        if (shouldShowTopBar) {
            mineViewContainer = new MineViewContainer(getActivity());
            mineViewContainer.setCallback(new MineViewContainer.Callback() {
                @Override
                public void showLoadingView(String msg) {
                    showLoading(msg);
                }

                @Override
                public void hideLoadingView() {
                    hideLoading();
                }

                @Override
                public void onClickButton() {
                    mDrawerLayout.closeDrawer(GravityCompat.START);
                }
            });
            FrameLayout frameLayout = findViewById(R.id.nav_view);
            mineViewContainer.attach(frameLayout);
        }


        getStatusBarHeight();
        swipeRefreshLayout = findViewById(R.id.swipe);
        initView();

        swipeRefreshLayout.setRefreshing(true);
        mDrawerLayout = findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, null, R.string.open_gps_service_content, R.string.open_gps_service_content);
        toggle.syncState();

        createPath();
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                devicePage = 1;
                getCameraList();
            }
        });
        getCameraList();


    }



    private void getStatusBarHeight() {
        statusBarHeight = (int) getResources().getDimension(R.dimen.status_bar_height);
        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight = getResources().getDimensionPixelSize(resourceId);
        }
    }

    public List<DeviceItem> getDeviceList() {
        return deviceList;
    }

    protected void listAdapter() {
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mAdapter = new DeviceListAdapter(getActivity(), deviceList);
        mAdapter.setDoorbellMaps(mDoorbellMaps);
        mAdapter.setHasStableIds(true);
        mAdapter.setOnItemClickListener(this, this);

        recyclerView.setAdapter(mAdapter);
        recyclerView.setLayoutManager(linearLayoutManager);
        isListDisplay = true;
    }

    private void initViewPager(){
        mViewPager = findViewById(R.id.banner_view);
        mViewPager.setIndicatorSliderGap(getResources().getDimensionPixelOffset(R.dimen.dp_8))
                .setScrollDuration(300)
                .setLifecycleRegistry(getLifecycle())
                .setIndicatorGravity(IndicatorGravity.CENTER)
                .setAdapter(
                        new ViewBindingSampleAdapter(getResources().getDimensionPixelOffset(R.dimen.dp_8)))
                .create(false);
        initRadioGroup();
        if (deviceList.size() > 1){
            mViewPager.setCurrentItem(0);
        }
    }



    private void initRadioGroup() {
        int checkedWidth = getResources().getDimensionPixelOffset(R.dimen.dp_4);
        mViewPager.setIndicatorStyle(IndicatorStyle.CIRCLE)
                .setIndicatorSlideMode(IndicatorSlideMode.WORM)
                .setIndicatorSliderGap(getResources().getDimensionPixelOffset(R.dimen.dp_6))
                .setIndicatorSliderRadius(checkedWidth, checkedWidth)
                .setIndicatorSliderColor(ResourcesUtil.getResources().getColor(R.color.red_normal_color), ResourcesUtil.getResources().getColor(R.color.red_checked_color))
                .refreshData(ImageUtils.getPicList(deviceList.size() + 1));

        mViewPager.setVisibility(deviceList.size() > MAX_PAGER || isListDisplay? View.GONE : View.VISIBLE);
    }

    protected void initView() {
        RelativeLayout topBarLayout = findViewById(R.id.rl_devicelist_toolbar);
        if (shouldShowTopBar) {
            topBarLayout.setVisibility(View.VISIBLE);
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) topBarLayout.getLayoutParams();
            params.topMargin = statusBarHeight;
            topBarLayout.setLayoutParams(params);
        } else {
            topBarLayout.setVisibility(View.GONE);
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
            params.topMargin = statusBarHeight + UIUtil.dip2px(getActivity(), 10);
            swipeRefreshLayout.setLayoutParams(params);
        }

        drawMenu = findViewById(R.id.draw_menu);
        btnDisplayChanged = findViewById(R.id.btn_device_list_display);
        recyclerView = findViewById(R.id.recycle);
        linearLayoutManager = new LinearLayoutManager(getActivity());

        ListPreloader.PreloadSizeProvider sizeProvider = new FixedPreloadSizeProvider(imageWidthPixels, imageHeightPixels);
        ListPreloader.PreloadModelProvider modelProvider = new MyPreloadModelProvider();
        RecyclerViewPreloader preloaded = new RecyclerViewPreloader<>(Glide.with(this), modelProvider, sizeProvider, 10 /*maxPreload*/);
        recyclerView.addOnScrollListener(preloaded);
        ((DefaultItemAnimator) Objects.requireNonNull(recyclerView.getItemAnimator())).setSupportsChangeAnimations(false);

        recyclerView.addItemDecoration(CommItemDecoration.createVertical(Color.TRANSPARENT, DimenUtil.dp2px(getActivity(), 20)));

        btnListAdd = findViewById(R.id.btn_device_list_item_add_list);
        btnCardAdd = findViewById(R.id.btn_device_list_item_add_card);
        emptyLayout = findViewById(R.id.lin_device_list_empty_add);

        initViewPager();
        btnListAdd.setOnClickListener(this);
        btnCardAdd.setOnClickListener(this);
        drawMenu.setOnClickListener(this);


        btnDisplayChanged.setOnClickListener(v -> {
            uploadLog("listDisplay");
            listDisplay(!isListDisplay);
        });


        buildAdpater();


    }

    protected void onSearchTextChanged() {

    }

    protected abstract void buildAdpater();

    protected void listDisplay(boolean isList) {
        isListDisplay = true;
        btnDisplayChanged.setImageResource(R.drawable.ic_tange_global_icon_by_row_list);
        listAdapter();
        PreferenceUtil.setBoolean(getActivity(), CommonConstants.PRE_DEVICE_LIST_SHOW, isList);
        if (deviceList.size() == 0) {
            emptyDisplay(isList);
        }

        mViewPager.setVisibility(deviceList.size() > MAX_PAGER || isListDisplay? View.GONE : View.VISIBLE);
    }

    protected void emptyDisplay(boolean isList) {
        if (isList) {
            btnListAdd.setVisibility(View.VISIBLE);
            btnCardAdd.setVisibility(View.GONE);
        } else {
            btnListAdd.setVisibility(View.GONE);
            btnCardAdd.setVisibility(View.VISIBLE);
        }
    }

    public abstract void getCameraList();

    public void updateUI() {
        swipeRefreshLayout.setVisibility(View.VISIBLE);
        swipeRefreshLayout.setRefreshing(false);
        swipeRefreshLayout.setColorSchemeResources(com.module.commonui.R.color.global_customize_main_color, com.module.commonui.R.color.global_customize_main_color, com.module.commonui.R.color.global_customize_main_color);
        if (deviceList.size() > 0) {
            mAdapter.notifyDataSetChanged();
            recyclerView.setVisibility(View.VISIBLE);
            emptyLayout.setVisibility(View.GONE);
            initRadioGroup();


        } else {
            recyclerView.setVisibility(View.GONE);
            emptyLayout.setVisibility(View.VISIBLE);
        }

        if (deviceCount == -1){
            deviceCount = deviceList.size();
        }

        if (mineViewContainer != null) {
            mineViewContainer.setDeviceCount(deviceCount);
        }
    }

    public int getDeviceCount() {
        return deviceCount;
    }

    public void setMineViewContainer(MineViewContainer mineViewContainer) {
        this.mineViewContainer = mineViewContainer;
    }

    @Override

    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.draw_menu) {
            onDrawerClicked();
        }  else if (id == R.id.btn_device_list_item_add_list || id == R.id.btn_device_list_item_add_card) {
            onViewClick();
        }
    }

    protected void onDrawerClicked() {
        if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
        } else {
            mDrawerLayout.openDrawer(GravityCompat.START);
        }
    }

    protected abstract boolean onBackKeyClicked();

    @Override
    public abstract void onItemClick(int position, int type);

    @Override
    public void onUpdate() {
        getCameraList();
    }


    /**
     * 打开一个设备，看视频
     */
    protected void openDevice(DeviceItem device, int type) {
        DeviceHelper.openDevice(getActivity(), device, type);
    }

    private void openMoreFuncPopWindow() {
        if (mMoreWindow == null) {
            View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.layout_popwindow_device_list_more, null);
            mMoreWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            mMoreWindow.setOutsideTouchable(true);
            mMoreWindow.setFocusable(true);
            mMoreWindow.setOnDismissListener(() -> {
                if (getActivity() == null || getActivity().isFinishing()) {
                    return;
                }

                WindowManager.LayoutParams lp=getActivity().getWindow().getAttributes();
                lp.alpha = 1f;
                getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                getActivity().getWindow().setAttributes(lp);
            });

        }
        View contentView = mMoreWindow.getContentView();

        ImageView imageView = contentView.findViewById(R.id.btn_icon_device_list_more_screen);
        TextView textView = contentView.findViewById(R.id.tv_icon_device_list_more_screen);
        ImageView displayImage = contentView.findViewById(R.id.btn_icon_device_list_more_display);
        TextView displayText = contentView.findViewById(R.id.tv_icon_device_list_more_display);

        contentView.findViewById(R.id.btn_icon_device_list_more_add).setOnClickListener(v -> addDevice());
        contentView.findViewById(R.id.tv_icon_device_list_more_add).setOnClickListener(v -> addDevice());
        if (isLocalList) {

            contentView.findViewById(R.id.card_mode_layout).setVisibility(View.GONE);
            contentView.findViewById(R.id.more_screen_layout).setVisibility(View.GONE);

            textView.setVisibility(View.GONE);
            imageView.setVisibility(View.GONE);
            displayImage.setVisibility(View.GONE);
            displayText.setVisibility(View.GONE);
        } else {

            contentView.findViewById(R.id.card_mode_layout).setVisibility(View.VISIBLE);
            contentView.findViewById(R.id.more_screen_layout).setVisibility(View.VISIBLE);

            if (!isListDisplay) {
                displayImage.setImageResource(R.drawable.ic_tange_global_pop_list_mode);
                displayText.setText(R.string.more_display_list);
            } else {
                displayImage.setImageResource(R.drawable.ic_tange_global_pop_card_mode);
                displayText.setText(R.string.more_display_card);
            }
            View.OnClickListener screenListener = v -> {
                goToMultiPlayerActivity();
                mMoreWindow.dismiss();
                uploadLog("more_multiplay");
            };
            View.OnClickListener displayListener = v -> {
                listDisplay(!isListDisplay);
                mMoreWindow.dismiss();
                uploadLog("more_display");

            };

            imageView.setOnClickListener(screenListener);
            textView.setOnClickListener(screenListener);
            displayImage.setOnClickListener(displayListener);
            displayText.setOnClickListener(displayListener);
        }

        setMoreWindowLocation();
    }

    private void setMoreWindowLocation() {

    }

    private int getMaxWidth(){
        View contentView = mMoreWindow.getContentView();
        TextView textView = contentView.findViewById(R.id.tv_icon_device_list_more_screen);
        TextView displayText = contentView.findViewById(R.id.tv_icon_device_list_more_display);
        TextView addText = contentView.findViewById(R.id.tv_icon_device_list_more_add);
        int maxWidth = 0;
        TextPaint paint = textView.getPaint();
        Rect bounds = new Rect();

        String text = textView.getText().toString().trim();
        paint.getTextBounds(text,0, text.length(),bounds);
        maxWidth = Math.max(maxWidth, bounds.width());
        TGLog.d("width = " + maxWidth);

        text = displayText.getText().toString().trim();
        paint.getTextBounds(text,0,text.length(),bounds);
        maxWidth = Math.max(maxWidth, bounds.width());
        TGLog.d("width = " + maxWidth);

        text = addText.getText().toString().trim();
        paint.getTextBounds(text,0,text.length(),bounds);
        maxWidth = Math.max(maxWidth, bounds.width());
        maxWidth += DimenUtil.dp2px(TGApplicationBase.getApplicationContext(), 5);
        TGLog.d("width = " + maxWidth);
        return maxWidth;
    }

    private void goToMultiPlayerActivity() {
        Intent listIntent = new Intent(getActivity(), MultiPlayerActivity.class);
        ArrayList<DeviceItem> items = new ArrayList<>(deviceList);
        listIntent.putParcelableArrayListExtra(MultiPlayerActivity.EXT_DEVICE_TTEMS, items);
        startActivity(listIntent);
    }

    private void addDevice() {
        onViewClick();
        mMoreWindow.dismiss();
        uploadLog("more_adddevice");
    }

    @Override
    public abstract void onViewClick();


    private void createPath() {
        String path = Environment.getExternalStorageDirectory().getPath();
        String fileName = path + File.separator + getString(R.string.app_name);
        File f = new File(fileName);
        if (!f.exists()) {
            f.mkdirs();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        dismissMoreWindow();
    }

    private void dismissMoreWindow() {
        if (mMoreWindow != null && mMoreWindow.isShowing()) {
            mMoreWindow.dismiss();
        }
    }

    protected void uploadLog(String btn) {
        LogUtils.onEventClickByName("device_list", btn);
    }


    private class MyPreloadModelProvider implements ListPreloader.PreloadModelProvider<String> {


        @NonNull
        @Override
        public List<String> getPreloadItems(int position) {
            if (position < deviceList.size()) {
                String url = deviceList.get(position).image_path;
                return Collections.singletonList(url);
            }
            return Collections.emptyList();
        }

        @Nullable
        @Override
        public RequestBuilder<?> getPreloadRequestBuilder(@NonNull String item) {
            return Glide.with(getActivity()).load(item);
        }
    }
}
